<?php
require 'User.php';
require_once '../modules/DatabaseManager/DatabaseManager.php';

/**
 * Description of UserManager
 *
 * @author Andre Biel, Timo Prüße
 */
class UserManager {

    private $DbManager = NULL;

    function __construct() {
        if ($this->DbManager == null) {
            $this->DbManager = new DatabaseManager();
        }
    }

    /**
     * Prüft ob der eingegebene Benutzer existiert
     * @param type $AUserName Benutzername
     * @param type $APassword Benutzerpasswort
     * @return boolean Gibt an ob der Benutzer existiert
     */
    public function isValidUser($AUserName, $APassword) {
        $ResObj = null;
        // CONNECT
        $this->DbManager->connect();
        // ABFRAGE
        $AUserName = mysql_real_escape_string($AUserName);
        $APassword = mysql_real_escape_string($APassword);
        $statement = 'SELECT COUNT(*) AS ANZAHL FROM tabp_users WHERE ' . 'NAME =\''
                . $AUserName . '\' AND PASSWORD = \'' . $APassword . '\' LIMIT 1';
        $ResObj = $this->DbManager->execSQL($statement);
        // DISCONNECT
        if(!$ResObj) {
            return false;
        }
        $this->DbManager->disconnect();
        $Anzahl = intval($ResObj[0]->ANZAHL);
        if ($Anzahl === 1)
            return true;
        else
            return false;
    }

    public function getUser($AUserName) {
        $AUserName = mysql_real_escape_string($AUserName);
        $statement = 'SELECT * FROM tabp_users WHERE Name = \'' . $AUserName . '\' LIMIT 1';
        $this->DbManager->connect();
        $ResObj = $this->DbManager->execSQL($statement);
        $this->DbManager->disconnect();
        return $ResObj;
    }
    
    public function updateLastSessionForUserId($AUserId) 
    {
        $now = date('Y-d-m H:i:s'); 
        
        $statement = 'UPDATE tabp_users SET LastLogin = \'' . $now . 
                '\' WHERE ID_User = \'' . $AUserId . '\'';
            
        require_once $_SERVER['DOCUMENT_ROOT'] . '/tabp/modules/DatabaseManager/DatabaseManager.php';  
        $dbMan = new DatabaseManager();
        $dbMan->connect();
        $dbMan->execSQL($statement);
        $dbMan->disconnect();
    }

    public function getLastSessionOfUserId($AUserId)
    {
        $statement = 'SELECT LastLogin FROM tabp_users WHERE ID_User = \'' . 
                $AUserId . '\'';
        
        require_once $_SERVER['DOCUMENT_ROOT'] . '/tabp/modules/DatabaseManager/DatabaseManager.php';   
        $dbMan = new DatabaseManager();
        $dbMan->connect();
        $data = $dbMan->execSQL($statement);
        $dbMan->disconnect();
        
        $date = null;
        if ($data)
        {
            $temp = strtotime($data[0]->LastLogin );
            $date = date('d.m.Y - H:i:s', $temp);
        }
        else
        {
           $date = 'N/A'; 
        }
        return $date;
    }
}
?>